package com.glodon.zhuanli.datatype.controller;


import com.glodon.framework.common.Constants;
import com.glodon.framework.common.util.DTOUtil;
import com.glodon.framework.common.util.support.DTOCallbackHandler;
import com.glodon.framework.web.util.ResponseParam;
import com.glodon.infrastructure.support.DefaultBaseController;
import com.glodon.zhuanli.datatype.entity.DbDataType;
import com.glodon.zhuanli.datatype.service.DbDatatypeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping(value=DbDatatypeController.BASE_PATH)
public class DbDatatypeController extends DefaultBaseController {

    /**
     * 当前模块跟路径
     */
    public static final String BASE_PATH = "datatype/db" ;

    @Autowired
    private DbDatatypeService dbDatatypeService ;

    public DbDatatypeController(){
        this.addDictionaryProperty("dbType" , "dbtype") ;
    }

    @RequestMapping(method=RequestMethod.GET)
    public ModelAndView index(){
        ModelAndView mv = new ModelAndView() ;
        //设置返回的主视图名称
        mv.setViewName("/datatype/dbdatatype_index");

        return mv ;
    }

    /**
     * 记录分页查询
     * @param pageNum 分页号，由0开始
     * @param pageSize 每页记录数，默认为10
     * @return
     * @throws Exception
     */
    @RequestMapping(value="query" , method=RequestMethod.POST)
    @ResponseBody
    public ResponseParam query(
            @RequestParam(required=false , value="pagenum" , defaultValue=""+Constants.DEFAULT_START_PAGE)
                    int pageNum ,
            @RequestParam(required=false , value="pagesize" , defaultValue=""+Constants.DEFAULT_PAGESIZE)
                    int pageSize) throws Exception {
        //获取查询参数
        Map<String, Object> searchParam = getParametersStartingWith(getServletRequest() ,  Constants.DEFAULT_SEARCH_PREFIX) ;
        //执行分页查询
        Page<DbDataType> dbDatatypePage = dbDatatypeService.queryByPage(searchParam , pageNum , pageSize) ;

        //数据库实体与前端展示字段之间的转换，需要指定前端展示需要的字段
        List<Map<String, Object>> dbDatatypeList = DTOUtil.toDTOExcludeFields( dbDatatypePage.getContent() ,
                null , getDtoCallbackHandler( )) ;

        return buildEasyUIPageResult( dbDatatypePage , dbDatatypeList ) ;
    }

    @RequestMapping(value={"edit" , "new" , "detail"})
    public ModelAndView detail(@RequestParam(required = false) String id) throws Exception{
        ModelAndView editView = new ModelAndView("/datatype/dbdatatype_edit") ;

        //对象类型
        Object resultItem = new DbDataType() ;

        if( StringUtils.isNotBlank(id) ){
            DbDataType dbDataType = dbDatatypeService.get(id) ;

            //覆盖实体对象
            resultItem = DTOUtil.toDTOExcludeFields( dbDataType , null , getDtoCallbackHandler() ) ;
        }

        //判断是否为只读模式，只有url中包含/detail才是只读模式
        editView.addObject( "detail" , getHttpServletRequest().getRequestURI().indexOf("/detail")!=-1 ) ;

        editView.addObject( "data" , resultItem ) ;

        return editView ;
    }
    /**
     * 保存实体对象 。在保存之前进行后端实体属性的验证，保证添加的数据符合业务要求。<br>
     * 如果实体id不为空，进行更新操作，否则进行添加。
     * @param dbDatatype
     * @return
     * @throws Exception
     */
    @RequestMapping(value="save" , method = RequestMethod.POST)
    @ResponseBody
    public ResponseParam save(@Valid DbDataType dbDatatype) throws Exception{
        //id不为空，进行更新操作，否则进行添加
        if(StringUtils.isNotBlank(dbDatatype.getId())){
            //由请求参数中获取需要更新的字段
            Set<String> updateFields = getHttpServletRequest().getParameterMap().keySet() ;
            //按照字段更新对象
            dbDatatypeService.update(dbDatatype , updateFields) ;

            return ResponseParam.updateSuccess() ;
        }else{
            dbDatatypeService.save(dbDatatype) ;
            return ResponseParam.saveSuccess() ;
        }
    }

    /**
     * 删除信息
     * @param ids
     * @return
     */
    @RequestMapping(value="delete" , method=RequestMethod.POST)
    @ResponseBody
    public ResponseParam delete(@RequestParam(required=true , value="ids") String ids){
        if(StringUtils.isBlank(ids)){
            return ResponseParam.deleteFail() ;
        }
        //执行删除
        dbDatatypeService.delete(ids.split(",")) ;

        return ResponseParam.deleteSuccess() ;
    }

    /**
     * 获取PO到DTO转换的接口。主要用于在前端展示数据之前首先将数据格式处理完成。
     * @return
     */
    public DTOCallbackHandler getDtoCallbackHandler() {
        //创建转换接口类
        DTOCallbackHandler dtoCallbackHandler = new DTOCallbackHandler() {
            @Override
            public void doHandler(Map<String, Object> dtoMap) {
            }
        };

        return getDTOCallbackHandlerProxy(dtoCallbackHandler) ;
    }

}